package org.ecloud.oauth.server.provider;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.util.StringUtil;
import org.ecloud.base.identifier.IdGenerator;
import org.ecloud.base.identifier.config.IdConfig;
import org.ecloud.oauth.server.config.TokenConfig;
import org.ecloud.oauth.server.service.IClientService;
import org.ecloud.oauth.server.service.IUserService;
import org.ecloud.redis.config.AppConfig;
import org.ecloud.redis.utils.RedisUtil;
import org.ecloud.utils.BeanUtil;
import org.ecloud.utils.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class BaseProvider {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	protected IUserService userService;
	@Autowired
	protected IClientService clientService;
	@Autowired
	protected TokenConfig tokenConfig;
	@Autowired
	protected AppConfig appConfig;
	@Autowired
	private IdGenerator idGenerator;
	@Autowired
	private IdConfig idConfig;
	
	protected String uuid(){
		if(IdConfig.TYPE_SNOWFLAKE.equalsIgnoreCase(idConfig.getType())){
			return idGenerator.getId();
		} else if (IdConfig.TYPE_UUID.equalsIgnoreCase(idConfig.getType())){
			return UUIDUtil.uuid();
		}
		
		return UUIDUtil.uuid();
	}
	
	protected void cleanAndCacheKeys(String key, String ... cacheKeys){
		cleanCacheKeys(key);
		cacheKeys(key, cacheKeys);
	}

	protected void cacheKeys(String key, String ... cacheKeys){
		if(StringUtil.isBlank(key) || BeanUtil.isEmpty(cacheKeys)) return;
		
		long size = RedisUtil.redisTemplateString.opsForList().rightPushAll(key, cacheKeys);
		RedisUtil.redisTemplateString.expire(key, tokenConfig.getRemind(), TimeUnit.SECONDS);
		logger.debug("{} size {}.", key, size);
	}

	protected void cleanCacheKeys(String key){
		if(StringUtil.isBlank(key)) return;
		
		long size = RedisUtil.redisTemplateString.opsForList().size(key);
		logger.debug("{} size {}.", key, size);
		List<String> keys = RedisUtil.redisTemplateString.opsForList().range(key, 0L, size);
		RedisUtil.redisTemplateString.delete(keys);
		RedisUtil.redisTemplateString.delete(key);
	}
	
}
